﻿//     Copyright (c) Microsoft Corporation.  All rights reserved.

using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;

namespace Microsoft.Gateway.Utils
{
    public class StringToCollectionConverter : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return ((objectType == typeof(List<string>) || objectType == typeof(string)));
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            List<string> collection = null;

            if (reader.TokenType == JsonToken.StartArray)
            {
                //deserialize array
                collection = serializer.Deserialize<List<string>>(reader);               
            }
            else if (reader.TokenType == JsonToken.Null)
            {
                collection = new List<string>();
            }
            else
            {
                //deserialize string
                collection = new List<string>();
                collection.Add(reader.Value as string);
            }

            return collection;
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var collection = value as IList<string>;

            if (collection != null && collection.Count == 1)
            {
                //serialize as string
                var singleItem = collection.First();
                serializer.Serialize(writer, singleItem);
            }
            else
            {
                //serialize array
                serializer.Serialize(writer, value);
            }
        }
    }
}

